package org.csu.mypetstore.aspect;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import org.csu.mypetstore.domin.Account;
import org.csu.mypetstore.domin.LogTable;
import org.csu.mypetstore.service.LogTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Timer;


@Aspect
@Component
@Slf4j
public class LogAspect {

    @Autowired
    LogTableService logTableService;
    @Pointcut("@annotation(org.csu.mypetstore.aspect.LogAnnotation)")
    public void pt(){}

    /**
     * 定义@Before增强，拦截带有@Log注解的方法，并记录操作日志
     */

    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint)throws Throwable{

        Object result=joinPoint.proceed();
        recordLog (joinPoint);
        return result;
    }

    private void recordLog(ProceedingJoinPoint joinPoint){

        // 获取Log注解信息
        MethodSignature signature=(MethodSignature) joinPoint.getSignature();
        Method method= signature.getMethod();
        LogAnnotation logAnnotation=method.getAnnotation(LogAnnotation.class);

        // 获取目标方法名
        String methodName = joinPoint.getSignature().getName();
        // 获取目标方法参数
        Object[] args = joinPoint.getArgs();
        // 获取目标方法所在类
        String className = joinPoint.getTarget().getClass().getName();

        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session=request.getSession();
        Account account=(Account) session.getAttribute("loginUser");

        String user;
        if(account==null){
            user="游客";
        }else {
            user=account.getUserid();
        }
        LogTable logTable=new LogTable(user,className,methodName,
                Arrays.toString(args),logAnnotation.module(),logAnnotation.operation(),date);

        logTableService.addLogTable(logTable);

    }
}
